package com.bestv.engine.sorter;

import com.bestv.engine.model.RecommendationItem;
import com.bestv.lucene.ProgramSearcher;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Henry on 14-6-24.
 */
public class GenreSorter implements Sorter {
    private String name;
    private String genre;

    public GenreSorter(String name, String genre) {
        this.name = name;
        this.genre = genre;
    }

    @Override
    public void sort(List<RecommendationItem> recommendationItemList) {
        ProgramSearcher searcher = new ProgramSearcher();
        for (RecommendationItem item : recommendationItemList) {
            double similarity = searcher.similarity(item.getId(), name, genre);
            item.setGenreScore(similarity);
        }
        Collections.sort(recommendationItemList, new GenreComparator());
    }

    private class GenreComparator implements Comparator<RecommendationItem> {

        @Override
        public int compare(RecommendationItem item1, RecommendationItem item2) {
            int result;
            if (item1 == null && item2 == null) {
                result = 0;
            } else if (item1 == null) {
                result = -1;
            } else if (item2 == null) {
                result = 1;
            } else {
                result = (int) Math.signum(item1.getGenreScore() - item2.getGenreScore());
            }
            return -1 * result;
        }
    }
}
